package com.rf.richfitwheel.workflow.controller;

import com.rf.richfitwheel.common.contants.Constant;
import com.rf.richfitwheel.common.utils.PageParameter;
import com.rf.richfitwheel.common.utils.PageUtils;
import com.rf.richfitwheel.common.utils.R;
import com.rf.richfitwheel.workflow.conf.IamPropertiesConfig;
import com.rf.richfitwheel.workflow.model.PortalTodoSendHis;
import com.rf.richfitwheel.workflow.service.PortalTodoSendHisService;
import com.rf.richfitwheel.workflow.service.impl.HttpEntityJsonUtil;
import net.sf.json.JSONObject;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.Date;

/**
 * @author hushouquan
 */
@RestController
@RequestMapping("/portalTodo")
public class PortalTodoSendHisController{
    protected static final Logger log = LoggerFactory.getLogger(PortalTodoSendHisController.class);
    
    @Autowired
    private PortalTodoSendHisService portalTodoSendHisService;
    @Autowired
    private IamPropertiesConfig iamPropertiesConfig;
    
    /**
     * 分页查询
     * @param pageParameter 参数
     * @return 查询结果
     */
    @PostMapping("/queryPagePortalTodoSendHis")
    public R queryPagePortalTodoSendHis(@RequestBody PageParameter<PortalTodoSendHis> pageParameter){
        PageUtils pages = portalTodoSendHisService.queryPagePortalTodoSendHis(pageParameter);
        return R.ok().put("page", pages);
    }
    
    /**
     * 重发这条记录
     * @param id 主键
     * @return 结果
     */
    @GetMapping("/reSendPortalTodoSendHis/{id}")
//    @RequiresPermissions("sys:portalTodo:reSend")
    public R reSendPortalTodoSendHis(@PathVariable("id") String id){
        try{
            PortalTodoSendHis portalTodoSendHis = portalTodoSendHisService.getPortalTodoSendHisById(id);
            if(Constant.COMMON_YES_OR_NO_YES.equals(portalTodoSendHis.getSuccess())){
                return R.error("该记录之前已成功发送，请勿重复发送");
            }
            StringEntity stringEntity = new StringEntity(portalTodoSendHis.getParamJson().toString(), ContentType.APPLICATION_JSON);
            try{
                CloseableHttpResponse response = HttpEntityJsonUtil.executeApi(portalTodoSendHis.getAccessKey(),
                        portalTodoSendHis.getSecretKey(), portalTodoSendHis.getAppId(), portalTodoSendHis.getHttpMethod(),
                        stringEntity, Collections.emptyMap(), iamPropertiesConfig.getUrl() + portalTodoSendHis.getApiUrl());
                int statusCode = response.getStatusLine().getStatusCode();
                String result = EntityUtils.toString(response.getEntity());
//            portalTodoSendHis.setSuccess(Constant.COMMON_YES_OR_NO_NO);
                if(HttpStatus.SC_OK == statusCode){
                    JSONObject jb = JSONObject.fromObject(result);
                    if(jb.containsKey("code") && jb.getInt("code") == HttpStatus.SC_OK){
                        portalTodoSendHis.setSuccess(Constant.COMMON_YES_OR_NO_YES);
                    }else{
                        log.warn("重新发送待办任务失败,{},{}", statusCode, result);
                    }
                }else{
                    log.warn("重新发送待办任务失败,{},{}", statusCode, result);
                }
            }catch(Exception e){
                log.error(e.getMessage(), e);
            }
            portalTodoSendHis.setLastTime(new Date());
            portalTodoSendHis.setSendCount(portalTodoSendHis.getSendCount() + 1);
            portalTodoSendHisService.updatePortalTodoSendHis(portalTodoSendHis);
            if(Constant.COMMON_YES_OR_NO_YES.equals(portalTodoSendHis.getSuccess())){
                return R.ok();
            }else{
                return R.error("重新发送待办任务失败");
            }
        }catch(Exception e){
            log.error("重发失败", e);
            return R.error("重新发送待办任务失败");
        }
    }
}
